package kr.co.casually;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import kr.co.casually.adapter.YouTubePlayListAdapter;
import kr.co.casually.types.YouTubePlay;
import kr.co.casually.xml.parser.YouTubePlayXMLHandler;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.ListActivity;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class YouTubePlayListActivity extends ListActivity implements
		OnClickListener, OnItemClickListener, OnScrollListener {
	ArrayList<YouTubePlay> youTubePlays = null;
	ArrayList<YouTubePlay> searchList = null;
	private YouTubePlayListAdapter adapter = null;
	private EditText etKeyWord = null;
	private ImageView btnSearch = null;

	private String gdataUrl = "http://gdata.youtube.com/feeds/api/videos";
	WaitDlg dlg = null;
	private AsyncTask<NameValuePair, Void, Boolean> asyncTask;
	private String keyword = "";
	private WaitProgressDialog waitProgressDialog;

	int startIndex = 0;
	int maxResults = 15;

	boolean endList = false;
	boolean scrollEnd = false;

	int totalResult = 0;

	/** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.youtube_play_list);
		initActivity();

	}

	private void initActivity() {
		keyword = getIntent().getExtras().getString("keyword");
		youTubePlays = new ArrayList<YouTubePlay>();
		searchList = new ArrayList<YouTubePlay>();
		etKeyWord = (EditText) findViewById(R.id.et_youtube_play_keyword);
		btnSearch = (ImageView) findViewById(R.id.bt_youtube_play_search);
		adapter = new YouTubePlayListAdapter(this, this, youTubePlays);
		setListAdapter(adapter);
		etKeyWord.setText(keyword);
		waitProgressDialog = new WaitProgressDialog();
		getListView().setOnItemClickListener(this);
		getListView().setOnScrollListener(this);
		btnSearch.setOnClickListener(this);
	}
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.bt_youtube_play_search:
			getListView().setSelectionAfterHeaderView();
			totalResult = 0;
			startIndex = 1;
			maxResults= 15;
			endList = false;
			scrollEnd = false;
			youTubePlays.clear();
			searchList.clear();
			search();
			break;

		default:
			break;
		}

	}

	private void search() {
		String keyword = "";
		String v = "2";

		try {
			keyword = URLEncoder.encode(etKeyWord.getText().toString().trim(),
					"UTF-8");
			NameValuePair[] nvps = getNameValuePairs(keyword, startIndex + "",
					maxResults + "", v);
			asyncTask = new YouTubePlayXMLParserTask().execute(nvps);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	private NameValuePair[] getNameValuePairs(String keyword,
			String startIndex, String maxResults, String v) {
		NameValuePair nvpKeyword = new BasicNameValuePair("q", keyword);
		NameValuePair nvpStartIndex = new BasicNameValuePair("start-index",
				startIndex);
		NameValuePair nvpMaxResults = new BasicNameValuePair("max-results",
				maxResults);
		NameValuePair nvpV = new BasicNameValuePair("v", v);
		NameValuePair[] nvpArray = { nvpKeyword, nvpStartIndex, nvpMaxResults,
				nvpV };
		return nvpArray;
	}

	private class YouTubePlayXMLParserTask extends
			AsyncTask<NameValuePair, Void, Boolean> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			waitProgressDialog.showProgressDialog(YouTubePlayListActivity.this,
					"", "wating...");
			searchList.clear();

		}

		@Override
		protected Boolean doInBackground(NameValuePair... arg0) {
			searchList = getSearchList(arg0);
			return (searchList != null && searchList.size() > 0) ? true : false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			waitProgressDialog.dismissProgressDialog();
			if (result) {
				updateUI(searchList);
			} else {
				Toast.makeText(YouTubePlayListActivity.this,
						getString(R.string.not_info), 1000).show();
			}
		}

	}

	private ArrayList<YouTubePlay> getSearchList(NameValuePair[] nameValuePairs) {

		try {


			StringBuilder sbNameValue = new StringBuilder();
			for (int i = 0; i < nameValuePairs.length; i++) {
				String div = "";
				if (i == 0) {
					div = "?";
				} else {
					div = "&";
				}
				sbNameValue.append(div + nameValuePairs[i].getName() + "="
						+ nameValuePairs[i].getValue());
			}
			URL url = new URL(gdataUrl + sbNameValue.toString());
			URLConnection connection;
			connection = url.openConnection();
			HttpURLConnection httpConnection = (HttpURLConnection) connection;

			int responseCode = httpConnection.getResponseCode();
			if (responseCode == HttpURLConnection.HTTP_OK) {
				InputStream in = httpConnection.getInputStream();

				StringBuffer sbResult = new StringBuffer();
				byte[] b = new byte[4096];
				for (int n; (n = in.read(b)) != -1;) {
					sbResult.append(new String(b, 0, n));
				}
				sbResult.toString();

				BufferedReader br = new BufferedReader(new StringReader(
						sbResult.toString()));
				InputSource is = new InputSource(br);

				/** Handling XML */
				SAXParserFactory spf = SAXParserFactory.newInstance();
				SAXParser sp = spf.newSAXParser();
				XMLReader xr = sp.getXMLReader();

				/** Send URL to parse XML Tags */
				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				YouTubePlayXMLHandler youTubePlayXMLHandler = new YouTubePlayXMLHandler();
				xr.setContentHandler(youTubePlayXMLHandler);
				xr.parse(is);
				String total = YouTubePlayXMLHandler.getTotalResult();
				if (total != null && !total.equals("")) {
					setTotalResult(total);
				} else {
					setTotalResult("0");
				}
				return youTubePlayXMLHandler.getList();

			}

		} catch (Exception e) {
			System.out.println("XML Pasing Excpetion = " + e);
		}
		return null;

	}

	private void setTotalResult(String total) {
		totalResult = Integer.valueOf(total);
	}

	private void updateUI(ArrayList<YouTubePlay> list) {
		for (int i = 0; i < list.size(); i++) {
			youTubePlays.add(list.get(i));
			adapter.notifyDataSetChanged();
		}
		if (totalResult <= youTubePlays.size()) {
			endList = true;
		}
		if(youTubePlays.size()+ maxResults > totalResult){
			maxResults = totalResult - youTubePlays.size();
		}
		
		scrollEnd = false;
		

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {

		startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(youTubePlays
				.get(position).getContentUrl())));

	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		boolean loadMore = /* maybe add a padding */
		firstVisibleItem + visibleItemCount >= totalItemCount;
		if (loadMore && !endList && !scrollEnd) {
			startIndex += 1;
			scrollEnd = true;
			search();
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}

}